<template>
  <div class="login_box">

    <div class="pic_box">
      <img src="../assets/img/logo.png" alt />
    </div>
    <el-form
      :model="loginForm"
      :rules="loginFormRule"
      ref="ruleForm"
      label-width="0px"
      class="demo-ruleForm login_form"
    >
      <el-form-item prop="username">
        <el-input v-model="loginForm.username" prefix-icon="fa fa-user"></el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input type="password" v-model="loginForm.password" prefix-icon="fa fa-lock"></el-input>
      </el-form-item>
      <el-form-item class="btns">
        <el-button type="primary" round @click="login">登录</el-button>
        <el-button type="info" round @click="handle1">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      loginForm: {
        username: 'admin',
        password: '123456'
      },

      loginFormRule: {
        username: [
          { required: true, message: '请输入账号~', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '亲~长度在 3 到 10 个字符',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请输入密码~', trigger: 'blur' },
          {
            min: 6,
            max: 16,
            message: '亲~长度在 6 到 16 个字符',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  methods: {

    handle1: function() {
      this.$refs.ruleForm.resetFields()
    },
    login() {
      //validate()方法是element-ui提供的表单验证方法,验证之前的验证是否成功,方法里面传一个回调函数,它会往里面传两个参数
      //验证成功,返回true.
      this.$refs.ruleForm.validate(async vali => {
        if (!vali) return
        // 发送ajax请求.用的axios,返回的数据里面只有data才是真实数据,所以用解构赋值把data赋值给了res
        //async await 是开启异步,不然的会是同步的,一般获取不到数据
        const { data: res } = await this.$http.post('login', this.loginForm)
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        console.log(res)
        this.$message.success(res.meta.msg)
        // 登录成功后在sessionstoryg里面存入token.
        window.sessionStorage.setItem('token', res.data.token)
        this.$router.push('/home')
      })
    }
  }
}
</script>

<style lang="less" scoped>
.login_box {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 450px;
  height: 300px;
  background-color: #fff;
  transform: translate(-50%, -50%);
  .pic_box {
    width: 130px;
    height: 130px;
    margin: 0 auto;
    border: 1px solid #eee;
    border-radius: 50%;
    padding: 10px;
    background-color: #fff;
    transform: translate(0, -50%);
    box-shadow: 0 0 10px #ddd;
    img {
      width: 100%;
      border-radius: 50%;
      background-color: #eee;
    }
  }
  .login_form {
    position: absolute;
    bottom: 0;
    width: 100%;
    padding: 0 20px;
    box-sizing: border-box;
    .btns {
      float: right;
    }
  }
}
</style>
